package cn.amaake.magicplugin.satoken.config;

import cn.amaake.magicplugin.satoken.interfaces.SatokenAbstract;
import cn.amaake.magicplugin.satoken.model.SatokenUser;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.context.ApplicationContext;
import org.ssssssss.magicapi.core.model.JsonBean;

import java.util.function.BiFunction;
import java.util.function.Supplier;

public class MagicSaOauth2Config {

    private final ApplicationContext applicationContext;

    private final SaOAuth2Config saOAuth2Config;

    public MagicSaOauth2Config(ApplicationContext applicationContext,SaOAuth2Config saOAuth2Config){
        this.applicationContext = applicationContext;
        this.saOAuth2Config = saOAuth2Config;
        init();
    }

    private void init(){
        // 配置：未登录时返回的View
        saOAuth2Config.setNotLoginView(new Supplier<Object>() {
            @Override
            public Object get() {
                return new JsonBean<>(1, "当前会话在OAuth-Server端尚未登录", JSONUtil.createObj().put("url", "/oauth2/doLogin"));
            }
        });
        // 配置：登录处理函数
        saOAuth2Config.setDoLoginHandle(new BiFunction<String, String, Object>() {
            @Override
            public Object apply(String name, String pwd) {

                SatokenAbstract satokenAbstract = applicationContext.getBean(SatokenAbstract.class);
                SatokenUser satokenUser = satokenAbstract.getSatokenUser(name, pwd, null, false);

                if (satokenUser != null) {
                    String id = satokenUser.getId();
                    StpUtil.login(id);
                    return new JsonBean<>(1, "登陆成功");
                }
                return new JsonBean<>(0, "账号名或密码错误");
            }
        });
        // 配置：确认授权时返回的View
        saOAuth2Config.setConfirmView(new BiFunction<String, String, Object>() {
            @Override
            public Object apply(String clientId, String scope) {
                return new JsonBean<>(1, "应用 " + clientId + " 请求授权：" + scope, JSONUtil.createObj().put("url", "/oauth2/doConfirm?client_id=" + clientId + "&scope=" + scope));
            }
        });
    }



}
